﻿using System;
using System.Collections.Generic;
using System.IO;
using Amba.Workflow.Models;
using Amba.Workflow.Services;
using Orchard.ContentManagement;
using Orchard.Forms.Services;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Tokens;
using Orchard.Workflows.Models;
using Orchard.Workflows.Services;

namespace Amba.Workflow.Activities
{
    public class WriteWorkflowLogActivity : Task
    {
        private readonly IEventLogService _worlflowLogService;
        private readonly ITokenizer _tokenizer;

        public WriteWorkflowLogActivity(IEventLogService worlflowLogService, ITokenizer tokenizer)
        {
            _worlflowLogService = worlflowLogService;
            _tokenizer = tokenizer;
            T = NullLocalizer.Instance;
            Logger = NullLogger.Instance;
        }

        public Localizer T { get; set; }
        public ILogger Logger { get; set; }

        public override string Name
        {
            get { return "WriteWorkflowLog"; }
        }

        public override LocalizedString Category
        {
            get { return T("Log"); }
        }

        public override LocalizedString Description
        {
            get { return T("Writes message to special workflow log"); }
        }

        public override string Form
        {
            get { return "WriteWorkflowLogActivityForms"; }
        }

        public override IEnumerable<LocalizedString> GetPossibleOutcomes(WorkflowContext workflowContext,
            ActivityContext activityContext)
        {
            return new[] {T("Done")};
        }

        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext,
            ActivityContext activityContext)
        {
            var body = activityContext.GetState<string>("LogMessage");

            if (workflowContext.Content != null)
                body = _tokenizer.Replace(body, BuildTokenContext(workflowContext.Content));

            _worlflowLogService.CreateEventLogRecord(new WorkflowLogRecord()
            {
                ActivityId = activityContext.Record.Id,
                WorkflowId = activityContext.Record.WorkflowDefinitionRecord.Id,
                Title = activityContext.Record.WorkflowDefinitionRecord.Name,
                LogMessage = body,
                LogUtcDate = DateTime.UtcNow
            });

            yield return T("Done");
        }

        private IDictionary<string, object> BuildTokenContext(IContent item)
        {
            return new Dictionary<string, object> {{"Content", item}};
        }
    }
}